package com.lagou.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @description:
 * @author: yx
 * @date: 2021/11/2 10:53
 */
public class ClientDemo {

    public static void main(String[] args) throws Exception {
        while (true) {
            //1. 创建socket对象,建立与服务端的连接
            Socket socket = new Socket("127.0.0.1", 8080);
            System.out.println("客户端建立连接成功");
            //2. 通过连接获取outputStream向服务端发送消息
            System.out.print("我: ");
            Scanner scanner = new Scanner(System.in);
            String msg = scanner.nextLine();
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(msg.getBytes());
            //3. 通过连接接受服务端发来的消息
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            System.out.println("服务端: " + new String(bytes, 0, read));
            socket.close();
        }
    }
}
